<?php 
	include_once('connection.php');
	include_once('session.php');
	if (isset($_POST) && ($_POST['action'] == 'create')) {
		include_once('../functions/categories.php');
		include_once('../functions/pagination.php');

		//Add a new category
		add_new_category($_POST['name'],$_POST['parentid'],$_POST['description'],$_POST['state']);
	}
	else if (isset($_POST) && ($_POST['action'] == 'reloadlist')) {
		include_once('../functions/categories.php');
		include_once('../functions/pagination.php');

		//Get categories list
		get_cats_list();
	}
	//Reload the categories table
	else if (isset($_POST) && ($_POST['action'] == 'reload')) {
		include_once('../functions/categories.php');
		include_once('../functions/pagination.php');
		//Get the categories
		get_categories($_POST['page'],$_POST['cats_per_page'],$_POST['conditions']);
	}
	//Load the category informations for edit panel
	else if (isset($_POST) && ($_POST['action'] == 'edit')) {
		include_once('../functions/categories.php');
		create_edit_panel($_POST[id]);
	}
	//Update the categories
	else if (isset($_POST) && ($_POST['action'] == 'update')) {
		include_once('../functions/categories.php');
		$id = $_POST['id'];
		$name = $_POST['name'];
		$description = $_POST['description'];
		$state = $_POST['state'];
		$parent_id = $_POST['parent_id'];
		update_cat($id,$name,$description,$state,$parent_id);
	}
	//Update the category state
	else if (isset($_POST) && ($_POST['action'] == 'updatestate')) {
		include_once('../functions/categories.php');
		update_category_state($_POST['id'],$_POST['state']);
	}
	//Update categories state
	else if (isset($_POST) && ($_POST['action'] == 'updatecatsstate')) {
		include_once('../functions/categories.php');
		update_cats_state($_POST['ids'],$_POST['state']);
	}
	//Delete the category
	else if (isset($_POST) && ($_POST['action'] == 'changeorder')) {
		include_once('../functions/categories.php');
		change_display_order($_POST['id'],$_POST['dir']);
	}
	//Delete the category
	else if (isset($_POST) && ($_POST['action'] == 'delete')) {
		include_once('../functions/categories.php');
		delete_categories($_POST['ids']);
	}
	else {
		include_once('functions/categories.php');
		include_once('functions/pagination.php');
	}
	//Get the categories by page
	function get_categories($page,$cats_per_page,$conditions='')
	{
		if ($conditions == '') {
			$conditions = 'WHERE c.state <> 3';
		}
		$cats_per_page = 5; //Set posts_per_page
		$from = ($page - 1)*$cats_per_page;
		$rows = get_categories_with_conditions($from,$cats_per_page,$conditions);
		$numCats = count_cats_with_conditions($conditions);
		create_categories_table($rows,$numCats,$from,$cats_per_page);
	}
	//Create categories table
	function create_categories_table($rows,$numCats,$from,$cats_per_page) {
		echo '<table width="100%" cellspacing="0" cellpadding="0" border="0" name="cats-table" id="cats-table">
				<thead>
					<tr>
						<th scope="col" width="4%"><input type="checkbox" id="checkall" onclick="checkAll(this);" /></th>
						<th scope="col" class="left">Title</th>
						<th scope="col" width="10%">Publish</th>
						<th scope="col" width="15%">Order</th>
						<th scope="col" width="8%">Level</th>
						<th scope="col" width="7%">Posts</th>
					</tr>
				</thead>';
		echo '<tfoot>';
		echo '<tr><td colspan="7"><div id="pagination">';
		pagination($numCats,$from,$cats_per_page);
		echo '</div></td></tr>';
		echo '</tfoot>';
		echo '<tbody>';
		$odd = 1;
		foreach ($rows as $row) {
			if ($row[state] == '1') {
				$state = "publish";
			} else {
				$state = "unpublish";
			}
			if ($odd == 1) {
				echo '<tr>';
				$odd = 0;
			}
			else {
				echo '<tr class="even">';
				$odd = 1;
			}
			//Count the posts in category
			$numPosts = count_posts_in_category($row[id]);
			//Show the post level
			$level = $row[cat_level];
			//Get the display order
			$parent_id = get_category_parent_id($row[id]); //Get parent_id
			$rank = intval(get_display_order_rank($parent_id,$row[display_order]));
			$childs_count = intval(count_category_childs($parent_id));
			if ($rank !== 1) {
				$up = '<a href="#up" onclick="display_order(\'up\',this);"><div class="up arrow">up</div></a>';
			}
			else {
				$up = '<div class="arrow">up</div>';
			}
			if ($rank < $childs_count) {
				$down = '<a href="#down" onclick="display_order(\'down\',this);"><div class="down arrow">down</div></a>';
			}
			else {
				$down = '<div class="arrow">down</div>';
			}

			$gi_title = '';
			for ($i = 0; $i < $level - 1; $i++) {
				$gi_title = $gi_title.'<span class="gi">&#108;&mdash;</span>';
			}
			echo '<td><input type="checkbox" value="'.$row[id].'" name="cb[]" onclick="isChecked(this.checked);" /></td>';
			echo '<td class="left">'.$gi_title.'<a href="#edit" onclick="editCategory(this);">'.$row[category_name].'</a></td>';
			echo '<td><div class="state '.$state.'" onclick="update_cat_state(this);"><span>'.$state.'</span></div></td>';
			echo '<td class="left">'.$up.$down.'<span class="display">'.$rank.'</span></td>';
			echo '<td>'.$level.'</td>';
			echo '<td>'.$numPosts.'</td>';
			echo '</tr>';
		}
		echo '</tbody>';
		echo '</table>';
	}
	//Create categories list
	function create_categories_list($name,$selected=0,$invalid_ids = '')
	{
		$ids = array();
		$len = 0;
		if ($invalid_ids !== '') {
			$ids = explode(',', $invalid_ids);
			$len = count($ids);
		}
		$rows = get_all_categories();
		if ($name == "categoryid") {
			echo '<select name="'.$name.'" id="'.$name.'" onchange="changeConditions();">';
			echo '<option value="0">- Select category -</option>';
		}
		else {
			echo '<select name="'.$name.'" id="'.$name.'">';	
			if ($name == "parentid")
				echo '<option value="0">No parent</option>';
		}
			
		foreach ($rows as $row) {
			//If is invalid ids
			for ($i = 0; $i < $len; $i++)
				if ($row[id] == $ids[$i])
					break;
			if ($i < $len)
				continue;
			if ($row[id] == $selected)
				echo '<option value="'.$row[id].'" selected>';
			else
				echo '<option value="'.$row[id].'">';
			$lvl = 1;
			while ($lvl < $row[cat_level]) {
				echo '<span>&ndash;&nbsp;</span>';
				$lvl = $lvl + 1;
			}
				
			echo $row[category_name].'</option>';
		}
		echo '</select>';	
	}
	//Add a new category
	function add_new_category($name,$parentid,$description,$state)
	{
		if (empty($name)) {
			echo 1;//Category name require
		}
		else {
			$parent_path = '';
			//Get parent category
			if ($parentid !== '0') {
				$parent = get_category_by_id($parentid);
				$parent_path = $parent[cat_path];
				//Invalid state
				if (intval($parent[state]) > intval($state)) {
					echo 2;
					return;
				}
				$cat_level = intval($parent[cat_level]) + 1;
				$cat_path = $parent[cat_path];				
			}
			else {
				$cat_level = 1;
				$cat_path = '';
			}
			$max_display_order = get_max_display_order($parent_path);
			$display_order = intval($max_display_order) + 1;
			//Update display_order

			$name = strip_tags($name);
			$name = mysql_real_escape_string($name);

			$description = strip_tags($description);
			$description = mysql_real_escape_string($description);
			
			//Update display_order
			update_display_order($max_display_order,1);
			//Insert new category
			$result = insert_category($name,$parentid,$cat_level,$cat_path,$display_order,$description,$state,$_SESSION['username']);
			if ($result !== 0) {
				
				echo 0; // Insert successful
			}
		}
	}
	//Get all categories and show as dropdown list
	function get_cats_list()
	{
		$rows = get_all_categories();
		foreach ($rows as $row) {
			echo '<option value="'.$row[id].'">';
			$i = 1;
			while ($i < $row[cat_level]) {
				echo '<span>&ndash;&nbsp;</span>';
				$i = $i + 1;
			}
			echo $row[category_name].'</option>';
		}
	}
	//Upate the category state
	function update_category_state($id,$state)
	{
		$parent_id = get_category_parent_id($id);
		if ($parent_id !== '0') {
			$parent = get_category_by_id($parent_id);
			if (intval($parent[state]) > intval($state)) {
				echo 0;
				return;
			}
		}
		$cat = get_category_by_id($id);
		//Update the category
		if ($state !== $cat[state]) {
			$res = update_categories_state($state,$cat[cat_path]);
			echo $res;
		}	
	}
	//Update the categories state
	function update_cats_state($ids,$state)
	{
		$list = explode(",",$ids);
		$count = 0;

		foreach ($list as $id) {
			$parent_id = get_category_parent_id($id);
			if ($parent_id !== '0') {
				$parent = get_category_by_id($parent_id);
				if (intval($parent[state]) > intval($state)) {
					echo 0;
					return;
				}
			}
			$cat = get_category_by_id($id);
			//Update the category
			if ($state !== $cat[state]) {
				$res = update_categories_state($state,$cat[cat_path]);
				$count += intval($res);
			}	
		}
		echo $count;
	}
	//Create edit panel
	function create_edit_panel($id)
	{
		$cat = get_category_by_id($id);
		$cat_path = $cat[cat_path];
		$rows = get_categories_by_path($cat_path);
		$invalid_ids = '';
		$len = count($rows);
		if ($len == 0)
			$invalid_ids = '';
		else {
			$invalid_ids = $rows[0][id];
			for ($i = 1; $i < $len; $i++)
				$invalid_ids = $invalid_ids.','.$rows[$i][id];
		}
?>
		<h2 id="cat-header">Edit category</h2>
		<div class="form-elements">
			<label for="cat-name">Category name</label>
			<input type="text" name="cat-name" id="cat-name" value="<?php echo $cat[category_name];?>" />
		</div><!-- End .form-elements-->
		<div class="form-elements">
			<label for="description">Description</label>
			<textarea name="cat-description" id="cat-description"><?php echo $cat[description];?></textarea>
		</div><!-- End .form-elements-->
		<div class="form-elements">
			<label for="state">State</label>
			<select name="new_state" id="new_state">
				<option value="1" <?php if ($cat[state] == '1') echo 'selected'; ?>>Publish</option>
				<option value="2" <?php if ($cat[state] == '2') echo 'selected'; ?>>Unpublish</option>
				<option value="3" <?php if ($cat[state] == '3') echo 'selected'; ?>>Trash</option>
			</select>
		</div><!-- End .form-elements-->
		<div class="form-elements">
			<label for="category">Parent</label>
			<?php create_categories_list("parentid",$cat[parent_id],$invalid_ids); ?>
		</div><!-- End .form-elements-->
		<div class="form-elements">
			<input type="button" id="submit" class="myButton" value="Update" onclick="update_category_info();" />
		</div><!-- End .form-elements-->
		<input type="hidden" name="cat_id" id="cat_id" value="<?php echo $id;?>" />
<?php
	}
	//Update the category
	function update_cat($id,$name,$description,$state,$parent_id)
	{
		$cat = get_category_by_id($id);
		$is_updated_info = 1;
		$is_updated_state = 1;
		$is_updated_parent = 1;
		$parent_path = '';
		if (($name == $cat[category_name]) &&($description == $cat[description]))
			$is_updated_info = 0;
		if ($parent_id == $cat[parent_id])
			$is_updated_parent = 0;
		else {
			if ($parent_id !== '0') {
				$parent = get_category_by_id($parent_id);
				$parent_path = $parent[cat_path];
				if (intval($parent[state]) > intval($state)) {
					echo -1;
					return;
				}
			}
		}
		if ($state == $cat[state])
			$is_updated_state = 0;
		else {
			if ($parent_id !== '0') {
				$parent = get_category_by_id($parent_id);
				if (intval($parent[state]) > intval($state)) {
					echo -1;
					return;
				}
			}
		}
		if ($is_updated_info == 0 && $is_updated_state == 0 && $is_updated_parent == 0){
			echo 0;
			return;
		}
		//Update the information
		if ($is_updated_info == 1)
			update_category_info($id,$name,$description);
		if ($is_updated_parent == 1) {
			//Get the categories
			$update_cats = get_categories_by_path($cat[cat_path]);
			$count = count($update_cats);

			//Update the display order
			$display_order = intval($cat[display_order]);
			update_display_order($display_order,-$count);
			$display_order = intval(get_max_display_order($parent_path));
			update_display_order($display_order,$count);

			//Update the category parent id
			update_category_parent_id($id,$parent_id);
			//The details
			$cat_level = 1;
			$cat_path = $id.'>';
			//Update the categories details
			foreach ($update_cats as $update_cat)
			{
				$par = get_category_parent_id($update_cat[id]);
				print_r($par);
				if ($par !== '0') {
					$parent = get_category_by_id($par);
					$cat_level = intval($parent[cat_level]) + 1;
					$cat_path = $parent[cat_path].$update_cat[id].'>';
				}
				$display_order += 1;
				update_category_details($update_cat[id],$cat_level,$cat_path,$state,$display_order);
			}
		}
		else 
			if ($is_updated_state == 1)
				update_categories_state($state,$cat[cat_path]);
		echo 1;
	}
	//Change the display order
	function change_display_order($id,$dir)
	{
		$cat1 = get_category_by_id($id);
		if ($dir == 'up') {
			$condition = 'c.display_order < '.$cat1[display_order].' ORDER BY display_order DESC';
		}
		else {
			$condition = 'c.display_order > '.$cat1[display_order].' ORDER BY display_order ASC';
		}
		//Get the cat need to change
		$cat2_id = get_near_category($cat1[parent_id],$condition);
		$cat2 = get_category_by_id($cat2_id);
		$value = intval($cat1[display_order]) - intval($cat2[display_order]);
		$count = 0;
		if ($dir == 'up') {
			$result = update_display_order_by_cat_path($cat1[cat_path],-$value);
			$value = intval($result);
			$count += intval($result);
			$result = update_display_order_by_cat_path($cat2[cat_path],$value);
			$count += intval($result);
		}
		else {
			$result = update_display_order_by_cat_path($cat2[cat_path],$value);
			$value = intval($result);
			$count += intval($result);
			$result = update_display_order_by_cat_path($cat1[cat_path],$value);
			$count += intval($result);
		}
		echo $count;
	}
	//Delete the categories
	function delete_categories($ids)
	{
		$list = sort_categories_by_level('('.$ids.')');
		$count = 0;
		foreach ($list as $item) {
			$res = count_posts_in_category($item[id]);
			if ($res > 0)
				continue;
			$res = count_cats_with_conditions('WHERE parent_id='.$item[id]);
			if ($res > 0)
				continue;
			$cat = get_category_by_id($item[id]);
			update_display_order(intval($cat[display_order]),-1); //Update the display order
			$res = delete_category($item[id]); //Delete this category
			if ($res > 0)
				$count++;
		}
		echo $count;
	}
 ?>
